public without sharing class SummaryStageWinRatioToOppHandler implements Triggers.handler{
    public void handle(){
        List<StageWinRate__c> stageWinRatioList = new List<StageWinRate__c>();
        Set<Id> oppIdSet = new Set<Id>();
        if(Trigger.isDelete){
            for(StageWinRate__c stageWinRatio : (List<StageWinRate__c>)Trigger.old)
            {
               // stageWinRatio.add(stageWinRatio);
                oppIdSet.add(stageWinRatio.Opportunity__c);
            }
        }else{
            for(StageWinRate__c stageWinRatio: (List<StageWinRate__c>)Trigger.new){
                //stageWinRatioList.add(stageWinRatio);
                oppIdSet.add(stageWinRatio.Opportunity__c);
            }
        }

        //System.debug(LoggingLevel.INFO, '*** stageWinRatioList: ' + stageWinRatioList);
        if(!oppIdSet.isEmpty())
        {
            Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([SELECT Id,StageName,StageCanChange__c,WinRatio__c,(SELECT Id, Name, Opportunity__c, WinRadioSum__c,CountChild__c from OpportunityStage__r) FROM Opportunity WHERE Id in: oppIdSet]);
            List<Opportunity> oppSet = new List<Opportunity>();
            for(Id oId : oppIdSet)
            {
                Opportunity o = oppmap.get(oId);
                String str ='';
                List<StageWinRate__c> swrList = o.OpportunityStage__r;
                System.debug('swrList:\n'+swrList);
                for(StageWinRate__c swr: swrList){
                    if(swr.CountChild__c >=1){   //存在阶段赢单率小组时才允许还切换到下一阶段
                        str = str+swr.Name+';';
                    }
                    if(o.StageName==swr.Name){
                        o.WinRatio__c=swr.WinRadioSum__c;
                        if((o.StageName == '合同签订' || o.StageName == '合作确认' ) && o.WinRatio__c == 0){
                            o.WinRatio__c = null;
                        }
                    }
                }
                
                o.StageCanChange__c = str;
                oppSet.add(o);
            }
            System.debug(LoggingLevel.INFO, '*** oppSet: ' + oppSet);
            if(!oppSet.isEmpty())
            {
                update oppSet;
            }
        }       

    }
}